package com.gxuwz.stats.service.excelhandler;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gxuwz.stats.entity.AcademicWork;
import com.gxuwz.stats.entity.CreativeAchievement;
import com.gxuwz.stats.entity.DecisionConsulting;
import com.gxuwz.stats.entity.dto.DecisionConsultingGxunDTO;
import com.gxuwz.stats.service.SheetHandler;
import com.gxuwz.stats.service.SheetName;
import com.gxuwz.stats.service.excelNewHandler.DecisionConsultGxunListener;
import com.gxuwz.stats.service.impl.DecisionConsultingServiceImpl;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
@SheetName("决策咨询类")
public class DecisionConsultHandler implements SheetHandler {
    @Autowired
    private DecisionConsultingServiceImpl workloadService;

//    @Override
//    public void handle(Sheet sheet) {
//        // 将 Apache POI 的 Sheet 转换为 EasyExcel 的输入流（伪代码）
//        InputStream inputStream = convertSheetToInputStream(sheet);
//        String sheetName = sheet.getSheetName();
//        // 判断 sheetName 是否为空或为默认名（如 Sheet1），决定是否指定
//        if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
//            // 指定 sheet 名
//            EasyExcel.read(inputStream, DecisionConsulting.class, new DecisionConsultListener(workloadService))
//                    .sheet(sheetName)
//                    .headRowNumber(1)
//                    .doRead();
//        } else {
//            // 不指定 sheet 名，默认第一个
//            EasyExcel.read(inputStream, DecisionConsulting.class, new DecisionConsultListener(workloadService))
//                    .sheet()
//                    .headRowNumber(1)
//                    .doRead();
//        }
//        // 使用 EasyExcel 读取数据
////        EasyExcel.read(inputStream, DecisionConsulting.class, new DecisionConsultListener(workloadService))
////                .sheet("决策咨询类")  // 指定 Sheet 名称
////                .headRowNumber(1) // 明确指定标题行
////                .doRead();
//    }

//    @Override
//    public List<String> getHeaderFields() {
//        return null;
//    }

    private InputStream convertSheetToInputStream(Sheet sheet) {
        // 实现将 POI Sheet 转换为 InputStream 的逻辑（可能需要借助临时文件）
        // 此处仅为示例，实际需根据业务实现
        try {
            Workbook workbook = sheet.getWorkbook();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            workbook.write(out);
            return new ByteArrayInputStream(out.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException("Sheet转换输入流失败", e);
        }
    }

//    @Override
    public ImportResultProvider handle(Sheet sheet, String username, String role, String department) {
        InputStream inputStream = convertSheetToInputStream(sheet);
        String sheetName = sheet.getSheetName();
        org.apache.poi.ss.usermodel.Row headerRow = sheet.getRow(0);
        if (headerRow == null) {
            throw new RuntimeException("Excel表格缺少表头，无法识别模板类型！");
        }
        java.util.List<String> headers = new java.util.ArrayList<>();
        for (org.apache.poi.ss.usermodel.Cell cell : headerRow) {
            headers.add(cell.getStringCellValue().trim());
        }

        boolean isOriginalTemplate = headers.contains("姓名") && headers.contains("成果名称");
        boolean isGxunTemplate = headers.contains("录入人") && headers.contains("报告名称") && headers.contains("采纳单位名称");

        ImportResultProvider listener;

        if (isOriginalTemplate) {
            listener = new DecisionConsultListener(workloadService, username, role, department);
            if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
                EasyExcel.read(inputStream, DecisionConsulting.class, (AnalysisEventListener<DecisionConsulting>) listener)
                        .sheet(sheetName)
                        .headRowNumber(1)
                        .doRead();
            } else {
                EasyExcel.read(inputStream, DecisionConsulting.class, (AnalysisEventListener<DecisionConsulting>) listener)
                        .sheet()
                        .headRowNumber(1)
                        .doRead();
            }
        } else if (isGxunTemplate) {
            listener = new DecisionConsultGxunListener(workloadService, username, role, department);
            if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
                EasyExcel.read(inputStream, DecisionConsultingGxunDTO.class, (AnalysisEventListener<DecisionConsultingGxunDTO>) listener)
                        .sheet(sheetName)
                        .headRowNumber(1)
                        .doRead();
            } else {
                EasyExcel.read(inputStream, DecisionConsultingGxunDTO.class, (AnalysisEventListener<DecisionConsultingGxunDTO>) listener)
                        .sheet()
                        .headRowNumber(1)
                        .doRead();
            }
        } else {
            throw new RuntimeException("无法识别的决策咨询导入模板，请检查表头！");
        }
        return listener;
    }
}
